var filename = '';
var path = '';
var final_filename = '';

var now;
var timestamp;
var expire = 0;

var host = '';
var aliurlJson = '';
var aliParam = {
    'key': '',
    'policy': '',
    'OSSAccessKeyId': '',
    'success_action_status': '200', //让服务端返回200,不然，默认会返回204
    'signature': '',
}

/**
 * 获取ali oss url
 */
function getUrl() {
    $.ajax({
        url: 'http://127.0.0.1:9000/v1/bases/aliurl',
        type: "get",
        async: false,
        dataType: 'jsonp',
        success: function(data) {
            alert(data);
        },
        error: function() {
            alert('error');
        }
    })
}

/**
 * 设置上传路径
 */
function set_dirname(p) {
    path = p;
}

/**
 * 判断ali url 是否过期，重新设置参数
 */
function set_ali_param() {
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3) {
        aliurlJson = getUrl();
        var obj = eval("(" + aliurlJson + ")");
        host = obj['host'];
        aliParam.policy = obj['policy'];
        aliParam.OSSAccessKeyId = obj['accessid'];
        aliParam.signature = obj['signature'];
        expire = parseInt(obj['expire']);
        return true;
    }
    return false;
}

/**
 * 生成固定长度的随机字符串
 */
function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

/**
 * 获得文件后缀名
 */
function get_suffix(filename) {
    var pos = filename.lastIndexOf('.')
    var suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

/**
 * 生成最终上传文件路径
 */
function set_final_filename(filename) {
    var suffix = get_suffix(filename);
    final_filename = path + random_string(10) + suffix;
}

/**
 * 获得文件最终上传url地址
 */
function get_upload_path() {
    return host + '/' + final_filename;
}

function set_upload_param(up, filename, ret) {
    if (ret == false) {
        set_ali_param();
    }
    if (filename != '') {
        set_final_filename(filename);
    }

    up.setOption({
        'url': host,
        'multipart_params': aliParam
    });

    up.start();
}